<template>
  <basic-container class="priceAssessPage">
    <el-row>
      <el-col :span="12" align="left">
        <el-button size="small" type="primary">评估价列表</el-button>
        <el-button size="small" @click="link('/wy-rent/price/list')">历史记录</el-button>
      </el-col>
      <el-col :span="12" align="right">
        <el-button size="small" type="primary" @click="link('/wy-rent/price/add')">新增评估价</el-button>
        <el-button size="small" @click="link('/wy-rent/price/import')">导入</el-button>
        <el-button size="small" @click="exportData()">导出</el-button>
      </el-col>
    </el-row>
    <el-row class="houseFilter">
      <el-col :span="12">
        <div class="selectFilter">
          <el-select clearable v-model="projectId" placeholder="请选择项目" @change="getBuildingList" size="small" filterable>
            <el-option :label="item.project_name" :value="item.project_id" v-for="item in projectList" :key="item.project_id" />
          </el-select>
          <el-select clearable v-model="buildingId" placeholder="请选择楼栋" @change="getHouseRentListNow" size="small">
            <el-option v-for="item in buildingList" :key="item.building_id" :label="item.building_name" :value="item.building_id" />
          </el-select>
        </div>
      </el-col>
      <el-col align="right" :span="12">
        <el-input
          v-halfCharCode
          class="searchInput"
          placeholder="搜索物业名称"
          prefix-icon="el-icon-search"
          clearable
          @change="getHouseRentListNow()"
          @clear="getHouseRentListNow()"
          v-model="houseName"
        />
      </el-col>
    </el-row>

    <div class="buildingInfo" :style="`--tabWidth: ${tabWidth}px`" v-loading="loading">
      <div class="headCell infoLeft" v-if="tableData.length">
        <p>单元</p>
        <p>楼层</p>
      </div>
      <div class="unitTab" v-if="tableData.length">
        <div class="top">
          <div class="arrow arrowPrev" @click.stop="unitScroll('prev')" v-if="units.length > 2">
            <i class="el-icon-arrow-left"></i>
          </div>
          <div class="scrollWrap" id="scrollWrap">
            <div class="navList" :style="{'left': `${offsetLeft}px`}">
              <div
                class="tabChildrenCard"
                :class="{'is-active': item.unit == activeUnit}"
                :key="item.index"
                v-for="item in units"
                @click="changeUnit(item.unit)"
              >{{item.unit}}单元</div>
            </div>
          </div>
          <div class="arrow arrowNext" @click.stop="unitScroll('next')" v-if="units.length > 2">
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>

        <div class="down">
          <el-tabs class="floorTab" v-model="activeFloor" tab-position="left">
            <el-tab-pane v-for="unitFloor in floors" :key="unitFloor.index" :name="unitFloor.floor">
              <span slot="label">
                <div class="tabChildrenCard">{{unitFloor.floor}}层</div>
              </span>

              <div class="dataList" :style="{width:`${tabWidth * 2}px` }">
                <div
                  class="tr"
                  v-for="floor in currentFloor.filter(it => it == activeFloor)"
                  :key="floor"
                  :style="`transform: translateX(${offsetLeft}px)`"
                >
                  <div class="td" v-for="unit in currentUnit" :key="unit">
                    <div class="flexWrap">
                      <div
                        class="roomItem"
                        :class="{ 'expire': priceItem.expire,'failure': priceItem.failure }"
                        v-for="(priceItem, ind) in currentPrices.filter(it => it.floor == floor && it.roomUnit == unit) || []"
                        :key="ind"
                        :title="priceItem.validDate ? '有效至:'+priceItem.validDate : ''"
                        @click="viewInfoHistory(priceItem.roomId)"
                      >
                        <div class="roomNum" :class="{noprice: !priceItem.price}">{{priceItem.propertyName}}</div>
                        <div class="roomINfo" v-if="priceItem.price">
                          <p>{{priceItem.buildingArea}} m²</p>
                          <p>市场评估租金单价：{{priceItem.price}}元/m²/月</p>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <Empty class="noData" v-if="tableData.length == 0" />
    </div>
    <priceInfoHistory ref="priceInfoHistory1" />
  </basic-container>
</template>

<script>
import { fetchPriceList, fetchPriceListNow, fetchProjectList, fetchBuildingList } from '../api/rent-price'
import priceInfoHistory from "./price-info-history.vue"
import moment from 'moment'

export default {
  name: 'rent-price',
  components: {
    priceInfoHistory,
  },
  data () {
    return {
      // 搜索关键词
      houseName: "",
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      projectId: "",
      projectList: [],
      buildingId: "",
      buildingList: [],
      units: [],
      currentUnit: [],
      floors: [],
      floorWidth: null,
      currentFloor: [],
      tableData: [],
      currentPrices: [],
      //tab选项卡宽度
      tabWidth: '550',
      //当前单元
      activeUnit: 0,
      //当前的层数
      activeFloor: 0,
      //滚动偏移值
      offsetLeft: 0,
      //加载动画
      loading: false
    }
  },

  mounted: function () {
    this.init();
  },
  methods: {
    // 页面初始化
    async init () {
      // 获取项目列表
      const res = await fetchProjectList()
      if (res.data.code === 0) {
        const projectList = res.data.data || [];
        this.projectList = projectList;
        if (projectList.length) {
          let projectId = projectList.shift().project_id
          // 获取楼栋列表
          this.getBuildingList(projectId, true)
        }
      }
    },
    /**
     * 获取建筑列表
     * projectId {String} 项目id
     * isInit {Boolean} 是否初始化请求
     */
    async getBuildingList (projectId = this.projectId, isInit = false) {
      const res = await fetchBuildingList({ projectId })
      if (res.data.code == 0) {
        let buildingList = res.data.data.map(item => ({ ...item, building_name: item.building_name || '暂无名称' }));
        this.buildingList = buildingList
        buildingList.length && isInit && this.getHouseRentListNow(buildingList[0].building_id)
      }
    },

    //查询定价列表
    getHouseRentListNow (buildingId = this.buildingId) {
      this.loading = true
      console.log(this.houseName)
      fetchPriceListNow({ buildingId, name: this.houseName }).then(response => {
        const { units, floors, prices } = response.data.data;

        //图形显示
        this.units = units.map((item, index) => ({ index, unit: item }));
        this.activeUnit = units[0];
        this.currentUnit = this.deepCopy(units);

        this.floors = floors.map((item, index) => ({ index, floor: item }));
        this.activeFloor = floors[0];
        this.currentFloor = this.deepCopy(floors);
        this.floorWidth = this.floors.length * 520;

        //循环表格
        prices.forEach(item => {
          //根据validDate判断即将到期和失效价格
          //即将到期：validDate存在并且距离今天小于30天
          //失效价格：validDate存在并且大于今天
          if (item.validDate) {
            const validDate = moment(item.validDate);
            let days = validDate.diff(moment(), 'days');
            item.expire = days < 30
            item.failure = days < 0
          } else {
            //到期
            item.expire = false
            //失效
            item.failure = false
          }
        });
        this.tableData = prices;
        this.currentPrices = this.deepCopy(prices);

        prices.length && this.$nextTick(() => {
          let buildingInfoRef = document.getElementById("scrollWrap").clientWidth
          this.tabWidth = Math.ceil(buildingInfoRef / 2)
        })
        this.loading = false
      }).catch(obj => {
        this.loading = false
      })
    },
    //单元改变
    changeUnit (unit) {
      this.activeUnit = unit
    },
    //楼层改变
    changeFloor ({ name }) {
      this.activeFloor = this.floors.find(item => item.floor == name).floor
    },
    //单元滚动
    unitScroll (type) {
      if (type === 'next' && Math.abs(this.offsetLeft) < this.tabWidth * (this.floors.length - 2)) {
        this.offsetLeft = this.offsetLeft - this.tabWidth
      }
      if (type === 'prev' && this.offsetLeft < 0) {
        this.offsetLeft = this.offsetLeft + this.tabWidth
      }
    },
    //导出调价记录
    exportData () {
      let params = { buildingId: this.buildingId, name: this.houseName }
      this.publicExport('最新价格列表', '/api/rentprice/houserentprice-download-new', params)
    },

    //查看定价历史信息
    viewInfoHistory (rentPriceId) {
      this.$message.closeAll()
      rentPriceId ? this.$refs.priceInfoHistory1.show(rentPriceId) : this.$message('此房间暂无价格评估信息');
    }

  }
}

</script>


<style lang="scss" scoped>
.priceAssessPage {
  /deep/ .container-wrap {
    min-height: 100%;
  }
  .noData {
    margin-top: 10%;
  }
  .houseFilter {
    .selectFilter {
      display: flex;
      align-items: center;
      .el-select {
        width: 230px;
      }
    }
    .searchInput {
      width: 250px;
    }
  }
  .floor {
    width: 100px;
    height: 60px;
    line-height: 60px;
    background-color: dodgerblue;
    float: top;
    border: solid 1px #999999;
    margin: 5px;
    text-align: center;
    vertical-align: middle;
    font-size: 16px;
  }

  .selectFloor,
  .selectUnit {
    background-color: #f59b3b;
  }

  .houseCell {
    width: 200px;
    height: 100px;
    float: left;
    border: solid 1px #999999;
    margin: 5px;
    text-align: center;
    vertical-align: middle;
    font-size: 16px;
  }

  .graphicList {
    background-color: #fff;
    padding: 10px 20px;
  }

  .houseFilter {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 20px;

    /deep/ .el-select {
      margin-right: 10px;

      .el-input__inner {
        border-radius: 3px;
        border: 1px solid #dcdfe6;
      }
    }
  }

  .buildingInfo {
    margin-top: 20px;
    position: relative;

    .headCell {
      width: 100px;
      height: 60px;
      position: absolute;
      top: 0;
      left: 0;
      background: #f9fafb
        linear-gradient(
          to top right,
          rgba(0, 0, 0, 0) 0%,
          rgba(0, 0, 0, 0) calc(50% - 1px),
          rgba(0, 0, 0, 1) 50%,
          rgba(0, 0, 0, 0) calc(50% + 1px),
          rgba(0, 0, 0, 0) 100%
        );
      p {
        display: block;
        line-height: 30px;
        padding: 0 20px;

        &:first-child {
          text-align: right;
        }
      }
    }

    .unitTab {
      .scrollWrap {
        overflow: hidden;
        position: relative;
        height: 60px;
        width: 100%;
        padding: 0 30px;
      }

      .arrow {
        width: 30px;
        height: 60px;
        position: absolute;
        top: 0;
        z-index: 2;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        i {
          font-size: 20px;
          color: #000;
        }
      }

      .arrowPrev {
        left: 120px;
      }

      .arrowNext {
        right: 0;
      }

      .navList {
        width: auto;
        position: absolute;
        left: 0;
        top: 0;
        clear: both;
        white-space: nowrap;
        transition: left 0.5s cubic-bezier(0.165, 0.84, 0.44, 1);
      }

      .top {
        height: 60px;
        width: 100%;
        padding-left: 120px;
        position: relative;

        .tabChildrenCard {
          display: inline-block;
          background: #f7f7f7;
          height: 60px;
          line-height: 60px;
          text-align: center;
          width: var(--tabWidth);
          border-radius: 3px 3px 0 0;
          cursor: pointer;

          &.is-active {
            background: #2a92d5;
            color: #fff;
          }
        }
      }
    }

    /deep/ .el-tabs.floorTab {
      margin-top: 20px;

      .el-tabs__header {
        width: 100px;
        padding: 20px 19px;
        background-color: #f9fafb;

        &.is-left {
          margin-right: 20px;
        }
      }

      .el-tabs__item {
        text-align: center;
        padding: 0;
        height: 64px;
        line-height: 64px;
        border: 1px solid #dcdfe6;
        border-bottom: none;
        color: #333;

        &:last-child {
          border: 1px solid #dcdfe6;
        }

        &.is-active {
          background: #2a92d5;
          color: #fff;
        }
      }

      .el-tabs__nav-prev,
      .el-tabs__nav-next {
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;

        i {
          font-size: 18px;
        }
      }
    }

    .dataList {
      overflow: hidden;
      position: relative;

      .tr {
        white-space: nowrap;
        transition: all 0.5s cubic-bezier(0.165, 0.84, 0.44, 1);
      }

      .td {
        width: var(--tabWidth);
        border-left: 1px solid #dcdfe6;
        display: inline-block;
        min-height: 1px;
      }

      .flexWrap {
        display: flex;
        flex-wrap: wrap;
      }

      .roomItem {
        border: 1px solid #dcdfe6;
        border-left: none;
        border-top: none;
        width: 50%;
        height: 120px;
        padding: 20px 20px;
        display: flex;
        align-items: center;
        position: relative;
        cursor: pointer;

        &:nth-child(-n + 2) {
          border-top: 1px solid #dcdfe6;
        }

        &.expire,
        &.failure {
          &::before {
            content: "";
            width: 0;
            height: 0;
            border-style: solid;
            border-width: 0 70px 70px 0;
            border-color: transparent #b69329 transparent transparent;
            position: absolute;
            right: 0;
            top: 0;
          }

          &::after {
            content: "即将到期";
            color: #fff;
            position: absolute;
            right: -6px;
            top: 0;
            transform: rotate(45deg);
            font-size: 12px;
            transform-origin: left;
          }
        }

        &.failure::after {
          content: "失效价格";
        }

        &.failure::before {
          border-color: transparent #dc3545 transparent transparent;
        }

        .roomNum {
          font-size: 18px;
          padding: 0 10px;
          height: 50px;
          border-right: 1px solid #ccc;
          display: flex;
          align-items: center;
          justify-content: center;
          white-space: pre-wrap;
          &.noprice {
            border: none;
            width: 100%;
            text-align: center;
          }
        }

        .roomINfo {
          padding-left: 10px;
          min-height: 50px;
          flex-grow: 1;
          width: 50%;
          flex-shrink: 0;
          display: flex;
          flex-direction: column;
          justify-content: center;
          p {
            font-size: 12px;
            color: #444;
            display: block;
            white-space: pre-wrap;
          }
        }
      }
    }
  }
}
</style>
